package com.lframework.jh.push.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.lframework.jh.push.core.exceptions.impl.DefaultClientException;
import com.lframework.jh.push.core.impl.BaseMpServiceImpl;
import com.lframework.jh.push.core.utils.CollectionUtil;
import com.lframework.jh.push.core.utils.IdUtil;
import com.lframework.jh.push.core.utils.ObjectUtil;
import com.lframework.jh.push.service.annotations.OpLog;
import com.lframework.jh.push.service.entity.SysRole;
import com.lframework.jh.push.service.entity.SysUserRole;
import com.lframework.jh.push.service.enums.OpLogType;
import com.lframework.jh.push.service.mappers.SysUserRoleMapper;
import com.lframework.jh.push.service.service.SysRoleService;
import com.lframework.jh.push.service.service.SysUserRoleService;
import com.lframework.jh.push.service.vo.user.SysUserRoleSettingVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

@Service
public class SysUserRoleServiceImpl extends
        BaseMpServiceImpl<SysUserRoleMapper, SysUserRole>
        implements SysUserRoleService {

    @Autowired
    private SysRoleService sysRoleService;

    @OpLog(type = OpLogType.SYS, name = "用户授权角色，用户ID：{}，角色ID：{}", params = {"#vo.userIds",
            "#vo.roleIds"}, loopFormat = true)
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void setting(SysUserRoleSettingVo vo) {

        for (String userId : vo.getUserIds()) {
            this.doSetting(userId, vo.getRoleIds());
        }
    }

    @Override
    public List<SysUserRole> getByUserId(String userId) {

        return doGetByUserId(userId);
    }

    protected void doSetting(String userId, List<String> roleIds) {

        Wrapper<SysUserRole> deleteWrapper = Wrappers.lambdaQuery(SysUserRole.class)
                .eq(SysUserRole::getUserId, userId);
        getBaseMapper().delete(deleteWrapper);

        if (!CollectionUtil.isEmpty(roleIds)) {
            Set<String> roleIdSet = new HashSet<>(roleIds);

            for (String roleId : roleIdSet) {
                SysRole role = sysRoleService.findById(roleId);
                if (ObjectUtil.isNull(role)) {
                    throw new DefaultClientException("角色不存在，请检查！");
                }

                SysUserRole record = new SysUserRole();
                record.setId(IdUtil.getId());
                record.setUserId(userId);
                record.setRoleId(role.getId());

                getBaseMapper().insert(record);
            }
        }
    }

    protected List<SysUserRole> doGetByUserId(String userId) {

        return getBaseMapper().getByUserId(userId);
    }
}
